#include <flache_debug.h>
#include <fuse.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>

static pthread_mutex_t output_mutex = PTHREAD_MUTEX_INITIALIZER;

void write_output( char* message )
{
    pthread_mutex_lock( &output_mutex );
    //struct tm *local;
    //time_t t;

    //t = time(NULL);
    //local = localtime( &t );

    FILE *outfile = fopen( "/home/mschaefer/Desktop/flache-out.txt", "a" );

    if ( outfile == NULL )
        return;

    //fprintf( outfile, "%s: %s\n", asctime(local), message );
    pid_t pid = fuse_get_context()->pid;
    
    fprintf( outfile, "%d: %s\n", (int)pid, message );
    fflush( outfile );
    fclose( outfile );

    pthread_mutex_unlock( &output_mutex );
}

void write_output2( char* message, char* message2 )
{
    char* msg = (char*)malloc( strlen( message ) + strlen( message2 ) + 1 );
    sprintf( msg, "%s%s", message, message2 );
    write_output( msg );
    free( msg );
}

void report_error( char* message, int err )
{
    char err_code[32];
    sprintf( err_code, "%d", err );

    char* err_header = "error: ";

    int len = strlen(err_header) + strlen(message) + 5 + strlen(err_code);
    char* msg = (char*)malloc( len );

    sprintf( msg, "%s%s (%s)", err_header, message, err_code );

    write_output( msg );

    free(msg);
}
